package com.yu.waterstation.system.common.aspectj;

import com.alibaba.fastjson.JSON;
import com.yu.waterstation.common.common.util.ip.IpUtil;
import com.yu.waterstation.common.common.util.servlet.ServletUtils;
import com.yu.waterstation.system.common.util.session.SessionUtil;
import com.yu.waterstation.system.modules.system.mapper.AdminLogMapper;
import com.yu.waterstation.common.entity.system.AdminLog;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

/**
 * 异步打印调用接口的日志
 */
@Aspect
@Component
public class LogAspect {

    @Resource
    private AdminLogMapper adminLogMapper;

    @Pointcut("@annotation(com.yu.waterstation.common.common.annotation.AdminLog)")
    public void adminLogPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "adminLogPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, jsonResult, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param exception 异常
     */
    @AfterThrowing(value = "adminLogPointCut()",throwing = "exception")
    public void doAfterThrowing(JoinPoint joinPoint, Exception exception)   {
        handleLog(joinPoint, null, exception);
    }


    @Async
    public void handleLog(final JoinPoint joinPoint, Object jsonResult, final Exception exception) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        HttpServletRequest request = ServletUtils.getRequest();
        AdminLog adminLog = new AdminLog();

        adminLog.setUsername(SessionUtil.getCurrentSysUserUsername(ServletUtils.getRequest()));
        adminLog.setApi("[" + request.getMethod() + "] " + request.getServletPath()); // eg: [POST] /system/user
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
        if (apiOperation != null)
            adminLog.setDetail(apiOperation.value());

        adminLog.setSuccess(exception == null); // 成功与否
        adminLog.setParams(Arrays.toString(joinPoint.getArgs())); // 请求参数
        adminLog.setResult(exception == null ?
                JSON.toJSONString(jsonResult) : StringUtils.substring(exception.getMessage(), 0, 2000));
        adminLog.setMethod(joinPoint.getTarget().getClass().getName() + "." + method.getName());
        adminLog.setIp(IpUtil.getIp(request)); // ip地址
        adminLog.setTimestamp(new Date());

        adminLogMapper.insert(adminLog);
    }

}
